package org.fnzn.web;

import java.io.IOException;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.fnzn.bean.SysBytearray;
import org.fnzn.service.SysBytearrayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.fnzn.core.Result;
import org.fnzn.exception.MyException;
import org.fnzn.util.ResultGenerator;
import org.fnzn.util.StringUtil;

@RestController
@RequestMapping("/sysFile")
public class SysUploadContorller {
	@Autowired
	private SysBytearrayService sysBytearrayService;
	
	@RequestMapping(value="/upload",method = RequestMethod.POST)
	public Result upload2(SysBytearray sysb, HttpServletRequest request) throws IOException {
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());	
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());			
				if (file != null) {
					byte[] bytes = file.getBytes();
					sysb.setBytes(bytes);
					if(StringUtils.isNotBlank(sysb.getId())){
						sysBytearrayService.update(sysb);
					}else{
						sysb.setId(StringUtil.getUUID());
						sysb.setBytes(bytes);
						sysBytearrayService.save(sysb);
					}				
				}else {
					throw new MyException("上传失败文件不存在");
				}
				// 记录上传该文件后的时间
				int finaltime = (int) System.currentTimeMillis();
				System.out.println(finaltime - pre);
				
			}

		}
		return ResultGenerator.genSuccessResult(sysb);
	}
	@RequestMapping(value="/getPic/{id}",method = RequestMethod.GET)
	public void getPic(HttpServletResponse resp,@PathVariable String id) throws IOException{
		SysBytearray sysb=sysBytearrayService.findById(id);
		if(sysb!=null){
			byte[] b =sysb.getBytes();
			resp.getOutputStream().write(b);
		}
		
	}

}
